<!-- cmx
     2024-12-05
	 数据渲染
	 是否登录判断
	 退出登录
 -->
<template>
	<view class="container">
		<!-- 头部个人信息卡片 -->
		<view class="header">
			<view class="avatar-box" @click="chooseAvatar">
				<image class="avatar" :src="userInfo.avatar || '../../static/1.png'" mode="aspectFill"></image>
				<!-- <image class="avatar" src="../../static/1.png" mode="aspectFill"></image> -->
				<view class="camera-icon">
					<uni-icons type="camera-filled" size="20" color="#FFFFFF"></uni-icons>
				</view>
			</view>
		</view>

		<!-- 设置列表 -->
		<uni-list>
			<!-- 基本信息组 -->
			<uni-list-item title="昵称" :rightText="userInfo.username || '去登录'" link showArrow @click="editNickname" />
			<uni-list-item title="密码设置" link showArrow @click="editPassword" />
			<uni-list-item title="手机号" :rightText="userInfo.tel || '去登录'" link showArrow @click="editPhone" />

			<!-- 账号关联组 -->
			<view class="gap"></view>
			<uni-list-item title="邮箱" :rightText="userInfo.email || '未绑定'" link showArrow />
			<uni-list-item title="微信绑定" :rightText="userInfo.wechat ? '已绑定' : '未绑定'" link showArrow />

			<!-- 其他信息组 -->
			<view class="gap"></view>
			<uni-list-item title="机构信息" link showArrow @click="editOrgInfo" />
			<uni-list-item title="个人信息" link showArrow />
			<uni-list-item title="我的简历" link showArrow />
			<uni-list-item title="我的投递" link showArrow />
		</uni-list>

		<!-- 退出登录按钮 -->
		<view class="logout-btn">
			<!-- <button type="default" @click="handleLogout">退出登录</button> -->
			<button type="default" :key="isLoggedIn" @click="handleClick">
			      {{ isLoggedIn() == -1 ? '去登录' : '退出登录' }}
			</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	// import { uni } from '@dcloudio/uni-app';

	// 定义用户信息数据
	/* const userInfo = ref({
	  avatar: '/static/mock-avatar.png', // 模拟头像数据
	  nickname: '',
	  phone: '',
	  email: '未绑定',
	  wechat: false,
	  orgInfo: {
	    name: 'XX科技有限公司',
	    role: '开发工程师'
	  }
	}); */

	const userInfo = ref({});

	// 获取用户信息
	const getUserInfo = async () => {
		const value = JSON.parse(uni.getStorageSync('id'));
		const userId = value[0].id;
		try {
			// 模拟API调用
			const res = await uni.request({
				url: `http://localhost:8080/user/findUserById`, // 使用模板字符串构建URL
				method: 'get', // 通常更新操作使用get方法
				header: {
					'content-type': 'application/x-www-form-urlencoded' // 设置内容类型为表单数据
				},
				data: {
					id: userId,
				},
			});
			userInfo.value = res.data;
			console.log(userInfo.value);
		} catch (e) {
			uni.showToast({
				title: '获取用户信息失败',
				icon: 'none'
			});
		}
	};

	// 选择头像
	const chooseAvatar = () => {
		uni.chooseImage({
			count: 1,
			success: async (res) => {
				const tempFilePath = res.tempFilePaths[0];
				try {
					// 模拟上传头像API
					await uni.$api.user.uploadAvatar({
						filePath: tempFilePath
					});
					userInfo.value.avatar = tempFilePath;
				} catch (e) {
					uni.showToast({
						title: '上传头像失败',
						icon: 'none'
					});
				}
			}
		});
	};

	// 修改昵称
	const editNickname = () => {
		console.log(userInfo.value);
		if (isLoggedIn() != -1) {
			uni.navigateTo({
				url: '/pages/account/edit-nickname'
			});
		} else {
			uni.navigateTo({
				url: '/pages/login/login'
			})
		}
	};

	// 修改密码
	const editPassword = () => {
		console.log(isLoggedIn());
		if (isLoggedIn() != -1) {
			uni.navigateTo({
				url: '/pages/passwordSetting/passwordSetting'
			});
		} else {
			uni.navigateTo({
				url: '/pages/login/login'
			})
		}
	};

	// 修改手机号
	const editPhone = () => {
		if (isLoggedIn() != -1) {
			uni.navigateTo({
				url: '/pages/account/edit-phone'
			});
		} else {
			uni.navigateTo({
				url: '/pages/login/login'
			})
		}
	};

	// 修改机构信息
	const editOrgInfo = () => {
		uni.navigateTo({
			url: '/pages/account/edit-org-info'
		});
	};

	// 退出登录
	const handleLogout = () => {
		uni.showModal({
			title: '提示',
			content: '确定要退出登录吗？',
			success: (res) => {
				if (res.confirm) {
					try {
						// 清除所有本地存储数据
						uni.clearStorageSync();

						// 重新启动应用并跳转到设置页面或登录页面
						uni.reLaunch({
							url: '/pages/account/settings' // 或者 '/pages/login/login'
						});
						uni.showToast({
							title: '退出登录成功',
							icon: 'none'
						});
					} catch (e) {
						// 错误处理
						console.error('退出登录失败:', e);
						uni.showToast({
							title: '退出登录失败，请稍后再试',
							icon: 'none'
						});
					}
				} else if (res.cancel) {
					// 用户点击取消后的逻辑（如果需要的话）
					console.log('用户点击取消');
				}
			}
		});
	};
	
	// 去登录
	const handleLogin = () => {
	  uni.navigateTo({
	    url: '/pages/login/login'
	  });
	};

	// 判断用户是否登录
	const isLoggedIn = () => {
		try {
			const storedUserInfo = uni.getStorageSync('id');
			console.log(storedUserInfo);
			if (storedUserInfo == null) {
				return -1;
			}

			const userInfo = JSON.parse(storedUserInfo);
			const now = Date.now();

			return userInfo && userInfo.id;
		} catch (error) {
			console.error('解析用户信息失败:', error);
			return -1;
		}
	};
	
	const handleClick = () => {
	  if (isLoggedIn() == -1) {
		  handleLogin();
	  } else {
	    handleLogout();
	  }
	};

	// 页面加载时获取用户信息
	onMounted(() => {
		getUserInfo();
	});
</script>

<style lang="scss">
	.container {
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	.header {
		padding: 40rpx 0;
		background-color: #ffffff;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.avatar-box {
		position: relative;
		width: 160rpx;
		height: 160rpx;
		border-radius: 50%;
		overflow: hidden;
	}

	.avatar {
		width: 100%;
		height: 100%;
	}

	.camera-icon {
		position: absolute;
		right: 0;
		bottom: 0;
		width: 40rpx;
		height: 40rpx;
		background-color: rgba(0, 0, 0, 0.5);
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.gap {
		height: 20rpx;
		background-color: #f5f5f5;
	}

	.logout-btn {
		margin: 60rpx 30rpx;

		button {
			background-color: #ffffff;
			color: #ff5a5f;
			font-weight: normal;

			&:active {
				opacity: 0.8;
			}
		}
	}
</style>